//
//  NewHomeViewController.m
//  NewPro
//
//  Created by RYX on 2019/4/18.
//  Copyright © 2019 何荧红. All rights reserved.
//

#import "NewHomeViewController.h"
#import "NewHomeHeaderView.h"
#import "NewHomeCell.h"
#import "NewHomeStore.h"
#import "NewHomeModel.h"
#import "HomeNews.h"
#import "NewHomeSearchView.h"
#import "HomeList.h"
#import "wkViewController.h"
#import "MineStore.h"
#import "UserModel.h"
#import "UINavigationBar+handle.h"
@interface NewHomeViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NewHomeHeaderView *headerView;
@property (nonatomic,strong) NewHomeSearchView *searchView;
@property (nonatomic,copy) NSArray *listArr;

@end

@implementation NewHomeViewController

- (NewHomeSearchView *)searchView{
    
    if (!_searchView) {
        
        _searchView = [[NewHomeSearchView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, iPhoneX_Top + 25)];
        MJWeakSelf
        [_searchView returnCloseBlock:^{
            
            weakSelf.searchView.height = iPhoneX_Top;
            [weakSelf.searchView layoutSubviews];
            
            weakSelf.headerView.imgView.collecBgView.height = iPhoneX_Top + 65;
            
        }];
    }
    
    return _searchView;
}

- (NewHomeHeaderView *)headerView{
 
    if (!_headerView) {
        
        CGFloat host_width = (ScreenWidth - 28) * 0.4 + 10 + 37;
        //1041
        _headerView = [[NewHomeHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1051 + host_width)];
    }
    return _headerView;
}
    
- (void)viewWillAppear:(BOOL)animated{
 
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:YES];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [self.navigationController.navigationBar navBarBackGroundColor:BLUECOLOR image:nil isOpaque:YES];
}

- (UITableView *)tableView{
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        _tableView.tableHeaderView = self.headerView;
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.edges.mas_equalTo(0);
        }];
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            [self loadData];
        }];
        header.lastUpdatedTimeLabel.hidden = YES;
        _tableView.mj_header = header;
        
        if (@available(iOS 11.0, *)) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
    }
    
    return _tableView;
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"首页";
    [self setUI];
    [self addNotification];
}

- (void)setUI{
    
    [self.tableView.mj_header beginRefreshing];
    [self.view addSubview:self.searchView];
}

- (void)addNotification{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestRealNameUrl) name:@"REALNAMEING" object:nil];
}

- (void)loadData{
    
    MJWeakSelf
    NewHomeStore *store = [[NewHomeStore alloc] init];
    [store getHomeInfoSuccess:^(NewHomeModel *model) {
        
        [weakSelf.tableView.mj_header endRefreshing];
        weakSelf.headerView.model = model;
        weakSelf.listArr = [HomeNews mj_objectArrayWithKeyValuesArray:model.news];
        [weakSelf.tableView reloadData];
        
    } Failure:^(NSError *error) {
        
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
    
    
    [store getRecommendListSuccess:^(NSArray *arr) {
        
        weakSelf.headerView.creditCardListArr = arr;
    } Failure:^(NSError *error) {
        
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
    
    //请求用户信息，得到实名认证标识
    [self requestRealNameUrl];
    
    //获取系统提示
    [self getNotice];
}

- (void)getNotice{
    
    MJWeakSelf
    NewHomeStore *store = [[NewHomeStore alloc] init];
    [store getHomeToastSuccess:^(NSString *title, NSString *content, NSString *uid) {
        
        NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
        NSString *closeSystemContent = [de objectForKey:@"closeSystemContent"];
        NSString *closeSystemId = [de objectForKey:@"closeSystemId"];
        
        if (!([closeSystemId intValue] == [uid intValue]) || ![closeSystemContent isEqualToString:content] || ![HomeList sharedInstance].closeToast) {
            
            NSString *str = [NSString stringWithFormat:@"%@                     %@                     %@                     %@                     %@                     ",content,content,content,content,content];
            weakSelf.searchView.notiStr = str;
            weakSelf.searchView.notiTitle = title;
            weakSelf.searchView.newsView.hidden = NO;
            weakSelf.searchView.height = iPhoneX_Top + 25;
            [weakSelf.searchView layoutSubviews];
            weakSelf.headerView.imgView.collecBgView.height = iPhoneX_Top + 65 + 25;
        }
        
    } Failure:^(NSError *error) {
        
        weakSelf.searchView.newsView.hidden = YES;
        weakSelf.searchView.height = iPhoneX_Top ;
        [weakSelf.searchView layoutSubviews];
        self.headerView.imgView.collecBgView.height = iPhoneX_Top + 65;
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 90;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.listArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NewHomeCell *cell = [NewHomeCell tempWithTableView:tableView];
    cell.model = self.listArr[indexPath.row];
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    wkViewController *VC = [[wkViewController alloc] init];
    [HomeList sharedInstance].selectedNew = self.listArr[indexPath.row];
    [VC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:VC animated:YES];
    
}

#pragma mark - 实名认证相关
- (void)requestRealNameUrl{
    
    MineStore *store = [[MineStore alloc] init];
    
    [store getUserInfoWithCustomId:[UserDefaultsManager sharedInstance].user_id Success:^(UserModel *model) {
        
        [HomeList sharedInstance].userModel = model;
        [UserDefaultsManager sharedInstance].real_name = model.realName;
        [HomeList sharedInstance].hadRealName = model.isSubmitRealNameAuthenticationed;
        
        NSString *str = [NSString stringWithFormat:@"%@",model.readnum];
        
        if (![str isEqualToString:@"0"] && ![str isEqualToString:@"(null)"]) {
            
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"HADNOREADTOMINE" object:nil];
            
            NSDictionary *dic = [NSDictionary dictionaryWithObject:str forKey:@"info"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"SETMINERED" object:nil userInfo:dic];
        }
        
    } Failure:^(NSError *error) {
        
    }];
}

#pragma mark - 滚动监听
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    [self.searchView.search resignFirstResponder];
    CGFloat offsetY = scrollView.contentOffset.y;
    CGFloat alpha = offsetY / 100;
    self.searchView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:alpha];
    [self.searchView setAalpha:alpha];
    
}
@end
